package com.example.mybatisdemo.interceptor;

import com.example.mybatisdemo.util.RedisUtils;
import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①:START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解，需要认证
        if (methodAnnotation != null) {
            String token = request.getHeader("token");
            if (StringUtils.isNullOrEmpty(token)) {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("必须先登陆");
                return false;
            }
            if (redisUtils.get(token) == null) {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("token失效");
                return false;
            }
            // 这写你拦截需要干的事儿，比如取缓存，SESSION，权限判断等
            //System.out.println("成功");
            return true;
        }
        return true;
    }
}
